#include "backuptable.h"
#include "ui_backuptable.h"

BackupTable::BackupTable(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::BackupTable)
{
    ui->setupUi(this);
    ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->scrollArea->installEventFilter(this);
    connect(ui->scrollArea->verticalScrollBar(), &QScrollBar::valueChanged,
            [this](int value) {
                if (value >= ui->scrollArea->verticalScrollBar()->maximum() - 10) {  // 距离底部10像素触发
                    emit refreshData();
                }
            });
    m_layout = new QVBoxLayout(ui->RecordArea);
    m_layout->setAlignment(Qt::AlignTop);
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_layout->setSpacing(0);

    m_animation = new QPropertyAnimation(ui->scrollArea->verticalScrollBar(), "value");
    m_animation->setDuration(500); // 动画时长（毫秒）

    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_addBackupRecord
            , this, &BackupTable::appendRecord);
    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_downloadFinished
            , this, &BackupTable::updateItemStatus);

}

BackupTable::~BackupTable()
{
    delete ui;
}

void BackupTable::appendRecord(const FileInfo &recordInfo)
{
    BackupRecordItem* newItem = new BackupRecordItem(nullptr, recordInfo);
    newItem->setFixedHeight(60);
    ui->RecordArea->setMinimumHeight(m_layout->count() * 60);
    m_layout->addWidget(newItem);

    // 连接选中状态变化信号
    QObject::connect(newItem, &BackupRecordItem::selectionChanged,
                     [this, newItem](bool selected) {
                         if (selected) {
                             if (!m_selectedRecords.contains(newItem))  {
                                 m_selectedRecords.append(newItem);
                             }
                         } else {
                             m_selectedRecords.removeAll(newItem);
                         }
                     });

    // 连接单个item删除的信号
    QObject::connect(newItem, &BackupRecordItem::deleteThisRecord,
                     this, &BackupTable::deleteRecord);

    //添加至下载集合
    connect(newItem, &BackupRecordItem::attemptToDownload,
            this, [this, newItem](){
                m_downloadRecords[newItem->getFileInfo().fileId] = newItem;
    });


}

QVector<BackupRecordItem *> BackupTable::getSelectedRecords() const
{
    return m_selectedRecords;
}

void BackupTable::selectAll()
{
    for (int i = 0; i < m_layout->count(); ++i) {
        if (auto item = qobject_cast<BackupRecordItem*>(m_layout->itemAt(i)->widget())) {
            item->setSelected(true);
        }
    }
}

void BackupTable::deselectAll()
{
    for (int i = 0; i < m_layout->count(); ++i) {
        if (auto item = qobject_cast<BackupRecordItem*>(m_layout->itemAt(i)->widget())) {
            item->setSelected(false);
        }
    }
}

void BackupTable::scrollToItem(qint64 fileId)
{
    QWidget* targetWidget;
    for (int i = 0; i < m_layout->count(); ++i) {
        if (auto item = qobject_cast<BackupRecordItem*>(m_layout->itemAt(i)->widget())) {
            if(item->getFileInfo().fileId == fileId){
                targetWidget = item;
            }
        }
    }
    scrollToWidget(targetWidget);
}

void BackupTable::scrollToItem(QString fileName)
{
    QWidget* targetWidget;
    for (int i = 0; i < m_layout->count(); ++i) {
        if (auto item = qobject_cast<BackupRecordItem*>(m_layout->itemAt(i)->widget())) {
            if(item->getFileInfo().logicalName.toStdString() == fileName.toStdString()){
                targetWidget = item;
            }
        }
    }
    scrollToWidget(targetWidget);
}

void BackupTable::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    QColor bgColor = QColor(255, 255, 255);
    painter.fillRect(rect(),  bgColor);

    QWidget::paintEvent(event);
}

void BackupTable::deleteAllSelected()
{
    // 使用临时副本防止迭代器失效
    auto selectedCopy = m_selectedRecords;

    for (auto item : selectedCopy) {
        m_layout->removeWidget(item);
        item->deleteLater();
        m_selectedRecords.removeAll(item);
    }

    // 更新容器高度
    ui->RecordArea->setMinimumHeight(m_layout->count() * 60);

    // 如果没有记录项了，隐藏滚动条
    if (m_layout->count() == 0) {
        ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    }
}

void BackupTable::downloadAllSelected()
{
    qDebug() << "Total" << m_selectedRecords.size()  << "records attempt to download";
}

void BackupTable::updateItemStatus(int file_id)
{
    auto it = m_downloadRecords.find(file_id);
    if(it != m_downloadRecords.end()){
        it.value()->setIsDownloaded(true);
    }
}

void BackupTable::deleteRecord(BackupRecordItem *recordItem)
{
    FileInfo info = recordItem->getFileInfo();
    //m_dao.deleteByFileId(info.fileId);
    //发送tcp请求删除记录

    m_layout->removeWidget(recordItem);
    recordItem->deleteLater();
}

void BackupTable::scrollToWidget(QWidget *target)
{
    if (!target) return;
    m_animation->stop();
    auto pos = target->mapTo(ui->scrollArea->viewport(), QPoint(0, 0));
    m_animation->setStartValue(ui->scrollArea->verticalScrollBar()->value());
    m_animation->setEndValue(pos.y());
    m_animation->start();
}
